//
// Created by andryu on 2025/1/1.
//
#include "RectangleRenderer.h"
#include "ShapeRenderer.h"
#include "../utils/ShaderLoader.h"
#include <android/log.h>
#include <string>

#define LOG_TAG "LabelSimple"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

//绘制顺序
GLushort drawOrder[] = {0,1,2,0,2,3};

RectangleRenderer::RectangleRenderer() {
    //四边形顶点坐标
    mVertices = {
            -0.5f,0.5f,0.0,
            -0.5f, -0.5f, 0.0,
            0.5f, -0.5f,0.0,
            0.5f,0.5f,0
    };
}

//着色器代码
std::string RectangleRenderer::getFragmentShaderCode() const {
    return R"(
        #version 100
        precision mediump float;
        uniform vec4 vColor;
        void main(){
            gl_FragColor = vColor;
        }
    )";
}

std::string RectangleRenderer::getVertexShaderCode() const {
    return R"(
        #version 100
        attribute vec4 vPosition;
        void main(){
            gl_Position = vPosition;
        }
    )";
}


void RectangleRenderer::onSurfaceCreated() {
    glClearColor(1.0,1.0,1.0,1.0);
    glClearDepthf(1.0);
    //启用深度测试
    glEnable(GL_DEPTH_TEST);
    //设置深度测试函数为“小于或等于”
    glDepthFunc(GL_LEQUAL);

    //加载并编译着色器
    //我们调用 glShaderSource 时，我们使用 c_str() 方法将 std::string 转换为 C 风格字符串，因为 glShaderSource 接受的是 const GLchar *const* 类型的参数。
    GLuint vertexShader = ShaderLoader::loadShader(GL_VERTEX_SHADER, getVertexShaderCode().c_str());
    GLuint fragmentShader = ShaderLoader::loadShader(GL_FRAGMENT_SHADER, getFragmentShaderCode().c_str());

    //创建着色器程序
    mProgram = glCreateProgram();
    glAttachShader(mProgram, vertexShader);
    glAttachShader(mProgram, fragmentShader);
    glLinkProgram(mProgram);

    //检查链接状态
    GLint linkStatus;
    glGetProgramiv(mProgram, GL_LINK_STATUS, &linkStatus);
    if (linkStatus == GL_FALSE){
        GLchar infoLog[512];
        glGetProgramInfoLog(mProgram,512, nullptr,infoLog);
        LOGD("Could not link program: %s", infoLog);
        glDeleteProgram(mProgram);
        mProgram = 0;
    }

    //删除不再需要的着色器
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
}

void RectangleRenderer::onSurfaceChanged(jint width, jint height) {

}

void RectangleRenderer::onDrawFrame() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //使用着色器程序
    glUseProgram(mProgram);

    //获取顶点属性位置
    GLint positionHandle = glGetAttribLocation(mProgram, "vPosition");
    glEnableVertexAttribArray(positionHandle);
    if (!mVertices.empty()) {
        glVertexAttribPointer(positionHandle, 3, GL_FLOAT, GL_FALSE, 0, mVertices.data());
    }

    //设置颜色
    GLfloat color[] = {0.63f, 0.76f, 0.22f, 1.0f};
    GLint colorHandle = glGetUniformLocation(mProgram, "vColor");
    glUniform4fv(colorHandle, 1, color);

    //绘制四边形
    glDrawElements(GL_TRIANGLES, 6,GL_UNSIGNED_SHORT,drawOrder);

    //禁用顶点数组
    glDisableVertexAttribArray(positionHandle);
}
